<?php

/**
 * NOTICE OF LICENSE
 *
 * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT.
 * 
 * DO NOT USE THIS FILE IN OTHER PLACE.
 *
 * @category  Poll_Parrots
 * @package   PollParrots
 * @author    cui cui <cui.yuhui@evebit.com>
 * @version   $$Id: IndexController.php 503 2010-05-06 09:58:27Z cui.yuhui $$
 * @copyright Copyright (c) 2008 Evebit Inc. China (http://www.evebit.com)
 */

/**
 * Derfault controller for user module 
 * 
 * @package PollParrots
 * @author  cui cui <cui.yuhui@evebit.com>
 * @version $$Id: IndexController.php 503 2010-05-06 09:58:27Z cui.yuhui $$
 */
class User_IndexController extends Evebit_Controller_Action_Frontend {
	
	/**
	 * user's home page
	 */
	function indexAction() {
		if (Zend_Auth::getInstance ()->hasIdentity ()) {
			$user = Zend_Auth::getInstance ()->getIdentity ();
			$this->view->user = $user;
		} else {
			$this->getSession ()->addError ( $this->__ ( "Please login at first!" ) );
			$configEntity = new Default_Model_Entity_Config ();
			$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
			;
		}
	}
	
	function myAccountAction() {
		if (Zend_Auth::getInstance ()->hasIdentity ()) {
			$user = Zend_Auth::getInstance ()->getIdentity ();
			$this->view->user = $user;
			
			$configEntity = new Default_Model_Entity_Config ();
			$paypalFee = $configEntity->getCodeValue ( 'paypal_fee' );
			$paypalAccount = $configEntity->getCodeValue ( 'paypal_account' );
			
			$emailHelper = new Evebit_Email_Helper ();
			$fullBasePath = $emailHelper->getFullBasePath ();
			
			$this->view->paypalFee = $paypalFee;
			$this->view->fullBasePath = $fullBasePath;
			$this->view->paypalAccount = $paypalAccount;
		}
	}
	
	/**
	 * login action of the index controller
	 * 
	 * login authentication
	 * 
	 */
	public function loginAction($data = null) {
		if (Zend_Auth::getInstance ()->hasIdentity ()){
			$this->getSession ()->addError ( 'You are successfully logged in' );
			
			$configEntity = new Default_Model_Entity_Config ();
			$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
		}
		$adapter = $this->getInvokeArg ( 'bootstrap' )->getResource ( 'auth' )->getAdapter ();
		
		$msg = 'Your registration is successful , You are successfully logged in';
		if (! $data) {
			$data = $this->getRequest ()->getPost ( 'data' );
			$msg = 'You are successfully logged in';
		}
		if (! count ( $data )) {
			return;
		}
		
		$adapter->setIdentity ( $data ['username'] );
		$adapter->setPassword ( $data ['password'] );
		$adapter->setIdentityField ( 'username' );
		$adapter->setIsGoogleLogin ( false );
		
		$auth = Zend_Auth::getInstance ();
		$result = $auth->authenticate ( $adapter );
		
		if ($result->isValid ()) {
			
			$this->getSession ()->addSuccess ( $msg );
			$result = $result->getIdentity ();
			$this->_redirect ( '/user/index/my-account' );
		} else {
			$resultcaptchaurltoken = $result->getIdentity ();
			if (empty ( $resultcaptchaurltoken ['url'] ) || empty ( $resultcaptchaurltoken ['token'] )) {
				$this->view->resultcaptchaurltoken = $resultcaptchaurltoken;
			}
			$this->getSession ()->addError ( implode ( '<br/>', $result->getMessages () ) );
			
			$configEntity = new Default_Model_Entity_Config ();
			$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
			;
		}
	
	}
	
	/**
	 * user logout
	 * 
	 */
	public function logoutAction() {
		Zend_Auth::getInstance ()->clearIdentity ();
		$this->getSession ()->addSuccess ( $this->__ ( "You are successfully logged out" ) );
		$configEntity = new Default_Model_Entity_Config ();
		$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
		;
	}
	
	/**
	 * validate data
	 * @param User_Model_Entity_User $user
	 * @param Array $data
	 */
	public function validateData($user, $data) {
		$id = null;
		if (isset ( $data ['id'] )) {
			$id = $data ['id'];
		}
		if (! $data ['username']) {
			$this->getSession ()->addError ( $this->__ ( "Username can not be empty!" ) );
			return false;
		}
		
		if (! $data ['email']) {
			$this->getSession ()->addError ( $this->__ ( "Email can not be empty!" ) );
			return false;
		}
		
		if ($user->isUserNameValid ( $data ['username'], $id )) {
			$this->getSession ()->addError ( $this->__ ( "Username already exists" ) );
			return false;
		}
		
		if ($user->isEmailValid ( $data ['email'], $id )) {
			$this->getSession ()->addError ( $this->__ ( "Email already exists" ) );
			return false;
		}
		
		if (isset ( $data ['confirm_password'] )) {
			if (trim ( $data ['password'] ) != trim ( $data ['confirm_password'] )) {
				$this->getSession ()->addError ( $this->__ ( "Password and Confirm Password not the same" ) );
				return false;
			}
		}
		
		return true;
	}
	
	public function editAction() {
		if (Zend_Auth::getInstance ()->hasIdentity ()) {
			$data = $this->getRequest ()->getPost ( 'data' );
			$user = new User_Model_Entity_User ();
			if (count ( $data )) {
				if (! $this->validateData ( $user, $data )) {
					$this->_redirect ( "/user/index/edit" );
				}
				if (isset ( $data ['confirm_password'] )) {
					unset ( $data ['confirm_password'] );
					if (! $data ['password']) {
						unset ( $data ['password'] );
					}
				}
				
				$user->addData ( $data );
				try {
					$user->save ();
					$this->getSession ()->addNotice ( $this->__ ( 'Edit successful.' ) );
				} catch ( Exception $e ) {
					$this->getSession ()->addError ( $this->__ ( "Edit failed" ) );
				}
			} else {
				$user = Zend_Auth::getInstance ()->getIdentity ();
			}
			$this->view->user = $user;
		} else {
			$this->getSession ()->addError ( $this->__ ( "Please login at first!" ) );
			$configEntity = new Default_Model_Entity_Config ();
			$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
			;
		}
	}
	
	/**
	 * user register
	 */
	public function registerAction() {
		if (Zend_Auth::getInstance ()->hasIdentity ()) {
			$this->getSession ()->addError ( $this->__ ( "You are successfully logged in" ) );
			$configEntity = new Default_Model_Entity_Config ();
			$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
			;
		}
		$data = $this->getRequest ()->getPost ( 'data' );
		
		$user = new User_Model_Entity_User ();
		if (! count ( $data )) {
			$this->view->assign ( 'fieldsets', $user->getFormField () );
			return;
		}
		
		if (! $this->validateData ( $user, $data )) {
			$this->_redirect ( "/user/index/register-" . strtolower ( $data ['select_role'] ) );
		}
		
		unset ( $data ['confirm_password'] );
		$user->addData ( $data );
		
		try {
			$user->save ();
			if ($data ['select_role'] != 'Entrepenuer') {
				$mailHelper = new Evebit_Email_Helper ();
				$result = $mailHelper->sendConfirmEmail ( $user );
				if ($result) {
					$this->getSession ()->addSuccess ( $this->__ ( 'We\'ll send a confirmation email to this address' ) );
					$configEntity = new Default_Model_Entity_Config ();
					$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
				} else {
					$user->delete ();
					$this->getSession ()->addError ( $this->__ ( "Registration failed." ) );
					$this->_redirect ( "/user/index/register-" . strtolower ( $data ['select_role'] ) );
				}
			} else {
			    $mailHelper = new Evebit_Email_Helper ();
				$result = $mailHelper->sendConfirmSuccessEmail ( $user );
				if (!$result) {
					$user->delete ();
					$this->getSession ()->addError ( $this->__ ( "Registration failed." ) );
					$this->_redirect ( "/user/index/register-" . strtolower ( $data ['select_role'] ) );
				}
				$this->loginAction ( $data );
			}
		
		} catch ( Exception $e ) {
			$user->delete ();
			$this->getSession ()->addError ( $this->__ ( "Registration failed." ) );
			$this->_redirect ( "/user/index/register-" . strtolower ( $data ['select_role'] ) );
		}
	}
	
	public function registerInvestorAction() {
		if (Zend_Auth::getInstance ()->hasIdentity ()) {
			$this->getSession ()->addError ( $this->__ ( "You are successfully logged in" ) );
			$configEntity = new Default_Model_Entity_Config ();
			$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
			;
		}
	}
	
	public function registerEntrepenuerAction() {
		if (Zend_Auth::getInstance ()->hasIdentity ()) {
			$this->getSession ()->addError ( $this->__ ( "You are successfully logged in" ) );
			$configEntity = new Default_Model_Entity_Config ();
			$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
			;
		}
	}
	
	/**
	 * Validate user name and password by AJAX for register
	 */
	public function ajaxValidateDataAction() {
		$id = $this->_getParam ( "id", null );
		$key = $this->_getParam ( "key", '' );
		$value = $this->_getParam ( "value", '' );
		
		$user = new User_Model_Entity_User ();
		if ($key == "username") {
			$result = $user->isUserNameValid ( $value, $id );
		} else {
			$result = $user->isEmailValid ( $value, $id );
		}
		$this->view->data = array ('result' => ($result ? 'failure' : "success") );
		$this->outputJson ();
	}
	
	/**
	 * confirm register
	 * 
	 */
	public function confirmAction() {
		$key = $this->getRequest ()->getParam ( "key", '' );
		$user = new User_Model_Entity_User ();
		if ($key == '' || ! $user->isConfirmkeyValid ( $key )) {
			$this->getSession ()->addError ( "Invalid Link" );
			$configEntity = new Default_Model_Entity_Config ();
			$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
			;
		}
		$user->load ( $key, 'confirm_key' );
		try {
			if ($user->getState () == 'confirming') {
				$password = $user->password;
				$user->unsetData ( 'password' );
				$user->setData ( 'state', 'normal' );
				$user->save ();
				$user->addData ( array ('password'=>$password ) );
				$mailHelper = new Evebit_Email_Helper ();
				$result = $mailHelper->sendConfirmSuccessEmail ( $user );
				if ($result) {
					/*$this->getSession ()->addSuccess ( "Your registration is successful, please login." );
					$configEntity = new Default_Model_Entity_Config ();
					$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );*/
					$this->loginAction ( $user->getData() );
				} else {
					$user->delete ();
					$this->getsession ()->addError ( $this->__ ( 'Sorry, the email sent failed' ) );
				}
			} else {
				$this->getSession ()->addError ( "Your account is already verified." );
			}
		} catch ( Exception $e ) {
			$this->getSession ()->addError ( "Confirmation failed." );
		
		}
		$configEntity = new Default_Model_Entity_Config ();
		$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
	}
	
	/**
	 * delete Account
	 */
	public function deleteAction() {
		$user = Zend_Auth::getInstance ()->getIdentity ();
		if ($user->delete ()) {
			$this->getSession ()->addSuccess ( $this->__ ( "Your account is deleted successfully." ) );
		} else {
			$this->getSession ()->addError ( $this->__ ( "Your account is failed to delete." ) );
		}
		$configEntity = new Default_Model_Entity_Config ();
		$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
		;
	}
	
	/**
	 * 
	 * forgot password
	 */
	public function forgotPasswordAction() {
		$data = $this->getRequest ()->getPost ( 'data' );
		if (! count ( $data )) {
			return;
		}
		$user = new User_Model_Entity_User ();
		$user->load ( $data ["email"], "email" );
		if ($user->getId () > 0) {
			$user->setData ( 'confirm_key', $user->getRandomKeys () );
			$user->setData ( 'lastest_modified', time () );
			$user->save ();
			$mailHelper = new Evebit_Email_Helper ();
			$result = $mailHelper->sendForgotPasswordEmail ( $user );
			if ($result) {
				$this->getSession ()->addNotice ( $this->__ ( "The email has been sent to " . $data ["email"] . " Please reset your password in 30 minutes." ) );
			} else {
				$user->delete ();
				$this->getsession ()->addError ( $this->__ ( 'Sorry, the email sent failed' ) );
			}
		} else {
			$this->getSession ()->addError ( $this->__ ( "Sorry, the email doesn't exist." ) );
		}
		$configEntity = new Default_Model_Entity_Config ();
		$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
		;
	}
	
	/**
	 * reset password
	 */
	public function resetPasswordAction() {
		$key = $this->_getParam ( "key" );
		$user = new User_Model_Entity_User ();
		if ($user->checkConfirmKey ( $key )) {
			if ($user->isTimeValid ()) {
				$data = $this->getRequest ()->getPost ( 'data' );
				if (! count ( $data )) {
					$this->view->assign ( 'confirm_key', $key );
					return;
				}
				if (empty ( $data ['password'] )) {
					$this->getSession ()->addError ( $this->__ ( "Password can not be empty!" ) );
					$this->_redirect ( '/user/index/reset-password/key/' . $key );
				}
				if ($data ['password'] == $data ['confirm_password']) {
					$user->setData ( 'password', $data ['password'] );
					try {
						$user->save ();
						$mailHelper = new Evebit_Email_Helper ();
						$result = $mailHelper->sendResetPasswordEmail ( $user );
						if ($result) {
							$this->getSession ()->addSuccess ( $this->__ ( "Password reset successes." ) );
						} else {
							$user->delete ();
							$this->getsession ()->addError ( $this->__ ( 'Sorry, the email sent failed' ) );
						}
					} catch ( Exception $e ) {
						$this->getSession ()->addError ( $this->__ ( "Operation failed" ) );
						$this->_redirect ( '/user/index/reset-password/key/' . $key );
					}
				} else {
					$this->getSession ()->addError ( $this->__ ( "Password and Confirm Password not the same" ) );
					$this->_redirect ( '/user/index/reset-password/key/' . $key );
				}
			} else {
				$this->getSession ()->addError ( $this->__ ( "Time out for validation." ) );
			}
		} else {
			$this->getSession ()->addError ( $this->__ ( "Invalid link" ) );
		
		}
		$configEntity = new Default_Model_Entity_Config ();
		$this->_redirect ( $configEntity->getCodeValue ( 'wp_base_url' ) );
		;
	}
	
	public function ajaxGetSessionAction() {
		$this->_helper->layout->disableLayout ();
	}
}
